/**
 *
 */
package fr.ece.ing4.chatapplication.server;

import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

import org.jgroups.Address;
import org.jgroups.Message;
import org.jgroups.View;

import fr.ece.ing4.chatapplication.api.ChatMessage;
import fr.ece.ing4.chatapplication.api.TransportDriver;
import fr.ece.ing4.chatapplication.api.TransportReceiver;

/**
 * @author enzo
 *
 */
public class ChatRoomController extends Observable implements TransportReceiver  {

    private String clusterName;
    private TransportDriver driver;
    private List<String>userList;
    private List<Address>addressList;

    public ChatRoomController(String chatroom, String name)
    {
        clusterName=chatroom;
        driver = new TransportDriver(clusterName,name,this);
        System.out.println("chatroomcreated");
        userList = new ArrayList<String>();
    }

    @Override
    public void printView(View v) {
        // TODO Auto-generated method stub
        System.out.println(""+v);

    }

    @Override
    //get the chatMessage and forward it to every people in the chatroom
    public void receiveChatMessage(Message msg) {
        // TODO Auto-generated method stub
        ChatMessage m =(ChatMessage) msg.getObject();
        if(m.getClusterName().equals(clusterName) && m.getType()== ChatMessage.CHAT && m.getFlag()==ChatMessage.SEND)
            forward(m);
        else if(m.getClusterName().equals(clusterName) && m.getType()== ChatMessage.CHAT && m.getFlag()==ChatMessage.RECV)
        {
            // on l affiche dans la vue serveur ?

        }

    }
    public void forward(ChatMessage msg)
    {
        StringBuilder sb= new StringBuilder();
        sb.append(msg.getSource().toString()).append(" > ").append(msg.getData());
        ChatMessage m= new ChatMessage(msg.getSource(),null,clusterName,msg.getType(),ChatMessage.RECV,sb.toString());
        driver.sendMessage(m);

    }
    /**
     * @return the clusterName
     */
    public String getClusterName() {
        return clusterName;
    }

    //update the userlist
    public void updateUserList(List<Address> list)
    { userList.removeAll(userList);
        addressList = list;
        for(Address a : list)
        {
            userList.add(a.toString());
        }
    }

    public void delete()
    {
        driver.disconnect();
    }

    public Address getUserAddress(String user)
    {
        for(Address a: addressList)
        {
            if(a.toString().equalsIgnoreCase(user)) return a;
        }
        return null;
    }
    @Override
    // each time a user connect/disconnect we update the list of usrs
    public void onViewChanged(View v) {
        // TODO Auto-generated method stub
        updateUserList(v.getMembers());

        notifyObservers(userList);
        this.setChanged();
    }

    /**
     * @return the addressList
     */
    public List<Address> getAddressList() {
        return addressList;
    }

}
